﻿using AutoMapper;
using D.B.Data.API.Applications.Command;
using D.B.Data.Domain;
using D.B.Data.ErrorCode;
using D.B.Data.Infrastructuse;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Yitter.IdGenerator;


namespace D.B.Data.API.Applications.CommandHandler
{
    public class AddUserCommandHandler : IRequestHandler<AddUserCommand, APIResult<int>>
    {
        private readonly IBaseRepository<UserModel> baseRepository;
        private readonly IMapper mapper;

        public AddUserCommandHandler(IBaseRepository<UserModel> baseRepository, IMapper mapper)
        {
            this.baseRepository = baseRepository;
            this.mapper = mapper;
        }

        public Task<APIResult<int>> Handle(AddUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> aPIResult = new();
            var res = baseRepository.GetAll().AsNoTracking().Where(s => s.UserName == request.UserName);
            if(res.Any())
            {


                aPIResult.Code = EnumCode.File;
                 aPIResult.Msg = "用户名称重复";
                return Task.FromResult(aPIResult);

            }
            var model = mapper.Map<UserModel>(request);

           
            model.CreateUserId = request.UserId;
            model.UpDataTime = null;
            model.UserPass = "12345678";
            int AddCount=baseRepository.Add(model);


            aPIResult.Code = EnumCode.Ok;
             aPIResult.Msg = "添加成功";
            aPIResult.Data = AddCount;
           

            return Task.FromResult(aPIResult);
        }
    }
}
